# -*- coding: UTF-8 -*-
import time
import sklearn.cluster
import requests
import pandas as pd
import json
ApiUrl = 'https://api.map.baidu.com/geocoding/v3/'  #百度API的url
AK = APIKEY  #百度密钥

# 获取地址对应的经纬度信息
def getlnglat(add):
    url = 'https://api.map.baidu.com/geocoding/v3/'
    params = { 'address' : add,
               'ak' : AK,          # 百度密钥
               'output': 'json'     }          # 输出结果设置为json格式
    res = requests.get(url, params)
    jd = json.loads(res.text)                 # 将json格式转化为Python字典
    return jd

# 获取地址对应的经纬度信息清单
def getlnglatlist(addrlist):
    addrloclist = []
    for addr in addrlist:
        addr = '上海市'+str(addr)
        try:
            loc = getlnglat(addr)['result']['location']
        except:
            time.sleep(2)
            try:
                loc = getlnglat(addr)['result']['location']
            except:
                loc['lng'] = ''
                loc['lat'] = ''
        item = [addr, loc['lng'], loc['lat']]
        addrloclist.append(item)
    return addrloclist




if __name__ == '__main__':
    df = pd.read_csv('data2/shanghai4月21日address.txt', names=['index', 'address'], skiprows=1)
    print(df.head())
    locationlist = getlnglatlist(df['address'])
    addrlocation = pd.DataFrame(locationlist, columns=['addr','lng','lat'])
    addrlocation.to_csv('shanghai4月21日addresslocation.csv')
    print(addrlocation.head(n=20))



    
